package com.vonchange.utils.template;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.vonchange.utils.map.HashMap;
import com.vonchange.utils.string.StringUtil;

/**
 * 简单模板实现
 * 
 * @author von_change@163.com
 * @date 2015-6-14 下午10:44:07
 */
public class TplUtil {
	/**
	 * 字符串占位符替换
	 * 
	 * @param tplStr
	 * @param data
	 * @return 替换过的String
	 */
	public static String tplByMap(String tplStr, Map<String, Object> data) {
		Matcher m = Pattern.compile("\\{([\\w\\.]*)\\}").matcher(tplStr);
		List<String> patternList = new ArrayList<String>();
		List<String> replaceStrList = new ArrayList<String>();
		while (m.find()) {
			String group = m.group();
			patternList.add(group);
			group = group.replaceAll("\\{|\\}", "");
			String value = "";
			if (null != data.get(group)) {
				value = String.valueOf(data.get(group));
			}
			replaceStrList.add(value);
			// tplStr = tplStr.replace(m.group(), value);
		}
		tplStr = StringUtil.replaceEach(tplStr, patternList.toArray(new String[patternList.size()]), replaceStrList.toArray(new String[replaceStrList.size()]));
		return tplStr;
	}

	public static String replaceAllByMap(String tplStr, Map<String, String> data) {
		List<String> patternList = new ArrayList<String>();
		List<String> replaceStrList = new ArrayList<String>();
		for (Entry<String, String> entry : data.entrySet()) {
			patternList.add(entry.getKey());
			replaceStrList.add(entry.getValue());
		}
		tplStr = StringUtil.replaceEach(tplStr, patternList.toArray(new String[patternList.size()]), replaceStrList.toArray(new String[replaceStrList.size()]));
		return tplStr;
	}

	public static void main(String[] args) {
        String  html="你好 ，{跑者} 安喜欢 赛小克 赛小赛小 ";
       // Map<String, String> data=new MyHashMap().set("{}", "ffff");
       String result=  replaceAllByMap(html, new HashMap<String,String>().set("{跑者}", "ffff").
    		   set("赛小", "返回"));
       System.out.println(result);
	}

	/**
	 * 数字替换{0}
	 * 
	 * @param str
	 * @param arr
	 * @return String
	 */
	public static String tplByArgs(String str, String... arr) {
		Matcher m = Pattern.compile("\\{(\\d)\\}").matcher(str);
		while (m.find()) {
			str = str.replace(m.group(), arr[Integer.parseInt(m.group(1))]);
		}
		return str;
	}

}
